package com.xxx.yuedong.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author HG
 * @version 1.0
 **/

/**
 * 消息发送确认
 */
@Configuration
@Slf4j
public class RabbitConfirmConfig {
    @Bean
    public RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);
        //设置开启Mandatory,才能触发回调函数，无论消息推送结果怎样都强制调用回调函数
        rabbitTemplate.setMandatory(true);

        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                log.debug("ConfirmCallback:      " + "相关数据：{}", correlationData);
                log.debug("ConfirmCallback:      " + "确认情况：{}", ack);
                log.debug("ConfirmCallback:      " + "原因：{}", cause);
            }
        });

        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                log.debug("ReturnCallBack:      " + "消息：{}", message);
                log.debug("ReturnCallBack:      " + "回应码：{}", replyCode);
                log.debug("ReturnCallBack:      " + "回应消息：{}", replyText);
                log.debug("ReturnCallBack:      " + "交换机：{}", exchange);
                log.debug("ReturnCallBack:      " + "路由键：{}", routingKey);
            }
        });

        return rabbitTemplate;
    }
}
